﻿using ConfExpert.Forms.Depo;
using ConfExpert.Properties;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Windows.Forms;

namespace ConfExpert.Entities
{
    public partial class DetailView : XPopupForm
    {
        int ProductId;
        Bitmap image;
        public DetailView(int productId)
        {
            InitializeComponent();
            ProductId = productId;
            this.Text += " - " + ProductId.ToString();
            //this.MouseWheel += new MouseEventHandler(DetailView_MouseWheel);

            this.FormBorderStyle = FormBorderStyle.FixedDialog;
        }

        BindingSource bs;
        Bitmap GetKumas()
        {
            if (d.Tables[0].Rows.Count > 0)
                if (d.Tables[0].Rows[0]["Photo"] != null)
                    if (d.Tables[0].Rows[0]["Photo"] != DBNull.Value)
                        return ((byte[])d.Tables[0].Rows[0]["Photo"]).ToBitmap();

            return Resources.coming_soon;
            //ds.xProductPhotos.FindByProductId(ProductId).Photo.ToBitmap();
        }

        DataSet d;
        private void DetailView_Load(object sender, EventArgs e)
        {
            Getir();

            ruler.Kumas = GetKumas();
            //ruler.ReDraw();
            
            ((RepositoryItemMemoEdit)txt.Edit).BorderStyle = BorderStyles.NoBorder;
            //((RepositoryItemMemoEdit)txt.Edit).Appearance.BackColor = Color.Transparent;

            txt.EditValue = d.Tables[1].Rows[0]["strVal"].ToStr();

            txt.EditWidth = 340;
            btn2x.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            if (d.Tables[1].Rows[0]["intVal"].ToInt() > 0)
            {
                btn2x.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                txt.EditWidth -= 70;
            } 


            //theImage = Image.FromStream(new MemoryStream(((byte[])((DataRowView)bsEkle.Current).Row["BLOB"])));

            this.SizeChanged += new EventHandler(DetailView_SizeChanged);
            ratio = Convert.ToDecimal(this.Height) / Convert.ToDecimal(this.Width);
            btn2x.ItemClick += btn2x_ItemClick;
            chkHatali.ItemClick += chkHatali_ItemClick;

            //Image img = CropFromCenter(Image.FromFile(@"I:\MyDISK\D\Users\Universal\Desktop\Yeni klasör\Article_39132.jpg"), 380);
            //KalikoImage sharpimg = new KalikoImage(img).GetThumbnailImage(400, 400, ThumbnailMethod.Crop);
            //sharpimg.SaveJpg(@"E:\kaliko.jpg", 90);
            //sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2, 0.5));

            image = new Bitmap(ruler.Kumas);

            if (image != null)
            {
                BitmapData bitmapData1 = image.LockBits(new Rectangle(0, 0,
                                         image.Width, image.Height),
                                         ImageLockMode.ReadOnly,
                                         PixelFormat.Format32bppArgb);

                TotalPixels = bitmapData1.Height * bitmapData1.Width;

                unsafe
                {
                    byte* imagePointer1 = (byte*)bitmapData1.Scan0;

                    for (int i = 0; i < bitmapData1.Height; i++)
                    {
                        for (int j = 0; j < bitmapData1.Width; j++)
                        {
                            Ekle1(Color.FromArgb(
                                imagePointer1[2],
                                imagePointer1[1],
                                imagePointer1[0])); //RGB
                            imagePointer1 += 4;
                        }

                        //4 bytes per pixel
                        imagePointer1 += bitmapData1.Stride - (bitmapData1.Width * 4);
                    }

                }

                image.UnlockBits(bitmapData1);
                unique0 = new Dictionary<Color, int>(unique1);
            }
            pnl.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
            trackBar1_ValueChanged(null, null);


            /*
            trackBar1.Visible = false;
            trackBar1.Minimum = 1;
            trackBar1.Maximum = 10;
            trackBar1.ValueChanged += trackBar1_ValueChanged;
            trackBar1.Value = 5;
            */

            int UserId = ExecuteScalar("GetTekrarTaranacaklarUserId", ProductId).ToInt();
            chkHatali.Checked = UserId > 0;
            chkHatali.Enabled = UserId == WhoAmI || UserId == 0 || ytk(17);
        }

        void chkHatali_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExecuteNonQuery("UpdTekrarTaranacaklar", ProductId, WhoAmI, chkHatali.Checked);
        }

        private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            // Create a local version of the graphics object for the PictureBox.
            Graphics g = e.Graphics;

            int x = 0;
            foreach (var item in unique2.OrderByDescending(i => i.Value))
            {
                if (item.Value * 100 / TotalPixels < 1)
                    break;

                System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(item.Key);
                g.FillRectangle(myBrush, new Rectangle(5, x * 25, 18, 18));
                g.DrawRectangle(BlackPen, new Rectangle(5, x * 25, 18, 18));
                //g.DrawString(BlackPen, (item.Value * 100 / TotalPixels).ToString(), MyFont, BlackBrush, new Point(x * 25, y * 60 + 25));
                g.DrawLine(RedPen, 5, x * 25 + 20, 5 + (item.Value * 20 / TotalPixels), x * 25 + 20);

                if (++x > 16)
                    break;
            }
        }

        Font MyFont = new Font("Calibri", 10);
        Pen BlackPen = new Pen(System.Drawing.Brushes.Black, 1);
        Pen RedPen = new Pen(System.Drawing.Brushes.Red, 2);
        Brush BlackBrush = System.Drawing.Brushes.Black;
        void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            tolerance = (15 * (255 * 255 * 3) / 500);

            unique1 = new Dictionary<Color, int>(unique0);
            unique2.Clear();

            foreach (var item in unique1.OrderByDescending(i => i.Value))
            {
                unique2.Add(item.Key, 0);
                break;
            }

            foreach (var item in unique1.OrderByDescending(i => i.Value))
                Ekle2(item.Key, item.Value);

            this.Invalidate();
        }


        public double distance(Color RGB1, Color RGB2)
        {
            double distance = 0;
            distance += Math.Pow(RGB1.R - RGB2.R, 2);
            distance += Math.Pow(RGB1.G - RGB2.G, 2);
            distance += Math.Pow(RGB1.B - RGB2.B, 2);
            return distance;
        }

        int TotalPixels;
        double tolerance = 0d;
        Dictionary<Color, int> unique0;
        Dictionary<Color, int> unique1 = new Dictionary<Color, int>();
        Dictionary<Color, int> unique2 = new Dictionary<Color, int>();
        void Ekle2(Color C, int f)
        {
            Dictionary<Color, double> dist = new Dictionary<Color, double>();
            foreach (Color clr in unique2.Keys)
                dist.Add(clr, distance(clr, C));

            foreach (var ret in dist.OrderBy(i => i.Value))
            {
                if (ret.Value <= tolerance)
                    unique2[ret.Key] += f;
                else
                    unique2.Add(C, f);

                break;  //sadece ilk elemanı işlesin diye
            }
        }

        void Ekle1(Color C)
        {
            if (unique1.ContainsKey(C))
                unique1[C] = ++unique1[C];
            else
                unique1.Add(C, 1);
        }

        void btn2x_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            using (Detail2x d2x = new Detail2x(ProductId))
                d2x.ShowDialog();

            GC.Collect();

            Cursor.Current = Cursors.Default;
        }

        decimal ratio = 1;

        private void Getir()
        {
            d = ExecuteDataSet("GetProductPhoto", ProductId, this.WindowState == FormWindowState.Maximized ? 1 : 0);
            bs = new BindingSource(d, d.Tables[0].TableName);

            ruler.ProductId = ProductId;
            prevState = this.WindowState;
        }

        FormWindowState prevState = FormWindowState.Normal;
        void DetailView_SizeChanged(object sender, EventArgs e)
        {
            this.SuspendLayout();
            bool stateChanged = this.WindowState != prevState;

            if (stateChanged)
                Getir();

            ruler.Kumas = GetKumas();

            if (stateChanged && prevState == FormWindowState.Normal)
                ruler.ReDraw();

            this.ResumeLayout();
        }


        void DetailView_MouseWheel(object sender, MouseEventArgs e)
        {
            if (e.Delta != 0 && (this.Height > 100 || e.Delta < 0))
            {
                this.SuspendLayout();
                this.Width -= e.Delta / 3;
                this.Height -= e.Delta / 3;
                this.ResumeLayout();
            }
        }


    }
}